package com.like.bluetooth.classic.client.scan.executor

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import com.like.bluetooth.callback.BluetoothCallback
import com.like.bluetooth.classic.client.scan.callback.ScanCallbackManager
import com.like.bluetooth.exception.BluetoothException
import com.like.bluetooth.util.ScanResult
import com.like.bluetooth.util.getBluetoothAdapter

/**
 * 蓝牙扫描的真正逻辑
 */
@SuppressLint("MissingPermission")
internal class ScanExecutor(context: Context) : BaseScanExecutor(context) {
    private val scanCallbackManager: ScanCallbackManager by lazy {
        ScanCallbackManager()
    }

    init {
        scanCallbackManager.registerBroadcastReceiver(mContext)
    }

    override fun onStartScan(
        onSuccess: ((ScanResult) -> Unit)?,
        onError: ((Throwable) -> Unit)?
    ) {
        val bluetoothCallback = object : BluetoothCallback<ScanResult>() {
            override fun onSuccess(data: ScanResult) {
                onSuccess?.invoke(data)
            }

            override fun onError(exception: BluetoothException) {
                // 这里不能直接抛异常，因为异步回调在另外的线程中，直接抛出了捕获不了，会造成崩溃。
                onError?.invoke(exception)
            }
        }
        scanCallbackManager.setScanBleCallback(bluetoothCallback)
        Log.i("ScanExecutor", "onStartDiscovery")
        // startDiscovery在大多数手机上是可以同时发现经典蓝牙和Ble的，但是它是通过注册广播接收器来接收扫描结果的，
        // 无法返回Ble设备的广播数据，所以无法通过广播识别设备，且startDiscovery扫描Ble的效率比StartLeScan低很多。
        val success = mContext.getBluetoothAdapter()?.startDiscovery() ?: false
        if (!success) {
            throw BluetoothException("开启扫描失败")
        }
    }

    override fun onStopScan() {
        mContext.getBluetoothAdapter()?.cancelDiscovery()
    }

    override fun close() {
        super.close()
        scanCallbackManager.unregisterBroadcastReceiver(mContext)
    }

}
